﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.Configuration;

public partial class CreateTestPage3Try : System.Web.UI.Page
{
    //public static string testId, copyTestId;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //testId = Request.QueryString["TestId"];
            //copyTestId = Request.QueryString["CopyTestId"];
            if ((Request.QueryString["TestId"] != null) && (Request.QueryString["TestId"] != ""))
                setControlValues();
            if ((Request.QueryString["CopyTestId"] != null) && (Request.QueryString["CopyTestId"] != ""))
                setCopyControlValues();
        }
    }

    private void setCopyControlValues()
    {
        DataTable dtTest = new DataTable();
        dtTest = AdminCreateTestDAL.GetTestInfoBasedOnTestId(Convert.ToInt32(Request.QueryString["CopyTestId"]));
        txtStartDate.Text = dtTest.Rows[0][10].ToString();
        txtEndDate.Text = dtTest.Rows[0][11].ToString();
        if (dtTest.Rows[0][13].ToString() == "1")
            chkSendCumulative.Checked = true;
        else
            chkSendCumulative.Checked = false;
        if (dtTest.Rows[0][14].ToString() == "1")
        {
            rdoLimited.Checked = true;
            chkSendCumulative.Visible = true;
        }
        else
        {
            rdoLimited.Checked = false;
            rdoUnlimited.Checked = true;
        }
        //string str = dtTest.Rows[0][17].ToString();
        //ddlAssignTask.SelectedIndex = ddlAssignTask.Items.IndexOf(ddlAssignTask.Items.FindByText(str));
        if (dtTest.Rows[0][18].ToString() == "1")
            chkNotify.Checked = true;
        else
            chkNotify.Checked = false;

        DataTable dtTestUser = new DataTable();
        dtTestUser = AdminCreateTestDAL.GetTestUserInfoBasedOnTestId(Convert.ToInt32(Request.QueryString["CopyTestId"]));
        StudentInfo[] s = new StudentInfo[dtTestUser.Rows.Count];
        UserSelection.sObj.Clear();
        for (int j = 0; j < dtTestUser.Rows.Count; j++)
        {
            s[j] = new StudentInfo();
            s[j].sid = dtTestUser.Rows[j][0];
            s[j].sname = dtTestUser.Rows[j][1].ToString();
            UserSelection.sObj.Add(s[j]);
        }
    }

    private void setControlValues()
    {
        DataTable dtTest = new DataTable();
        dtTest = AdminCreateTestDAL.GetTestInfoBasedOnTestId(Convert.ToInt32(Request.QueryString["TestId"]));
        txtStartDate.Text = dtTest.Rows[0][10].ToString();
        txtEndDate.Text = dtTest.Rows[0][11].ToString();
        if (dtTest.Rows[0][13].ToString() == "1")
            chkSendCumulative.Checked = true;
        else
            chkSendCumulative.Checked = false;
        if (dtTest.Rows[0][14].ToString() == "1")
        {
            rdoLimited.Checked = true;
            chkSendCumulative.Visible = true;
        }
        else
        {
            rdoLimited.Checked = false;
            rdoUnlimited.Checked = true;
        }
        string str = dtTest.Rows[0][17].ToString();
        ddlAssignTask.SelectedIndex = ddlAssignTask.Items.IndexOf(ddlAssignTask.Items.FindByText(str));
        if (dtTest.Rows[0][18].ToString() == "1")
            chkNotify.Checked = true;
        else
            chkNotify.Checked = false;


        DataTable dtTestUser = new DataTable();
        dtTestUser = AdminCreateTestDAL.GetTestUserInfoBasedOnTestId(Convert.ToInt32(Request.QueryString["TestId"]));
        StudentInfo[] s = new StudentInfo[dtTestUser.Rows.Count];
        UserSelection.sObj.Clear();
        for (int j = 0; j < dtTestUser.Rows.Count; j++)
        {
            s[j] = new StudentInfo();
            s[j].sid = dtTestUser.Rows[j][0];
            s[j].sname = dtTestUser.Rows[j][1].ToString();
            UserSelection.sObj.Add(s[j]);
        }
    }

    private void clearAll()
    {
        txtStartDate.Text = "";
        txtEndDate.Text = "";
        txtStartDate.Text = "";
        txtEndDate.Text = "";
        ddlAssignTask.SelectedIndex = -1;
        chkNotify.Checked = false;
        chkSendCumulative.Checked = false;
    }
    protected void btnClear_Click(object sender, EventArgs e)
    {
        clearAll();
    }

    protected void rdoUnlimited_CheckedChanged(object sender, EventArgs e)
    {
        if (rdoUnlimited.Checked == true)
        {
            chkSendCumulative.Checked = false;
            chkSendCumulative.Visible = false;
        }
    }
    protected void rdoLimited_CheckedChanged(object sender, EventArgs e)
    {
        if (rdoLimited.Checked == true)
        {
            chkSendCumulative.Visible = true;
        }
        
    }

    public static bool SendEmail(string pGmailEmail, string pGmailPassword, string pTo, string pSubject, string pBody, System.Web.Mail.MailFormat pFormat, string pAttachmentPath)
    {
        try
        {
            System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage();
            myMail.Fields.Add
                ("http://schemas.microsoft.com/cdo/configuration/smtpserver",
                              "smtp.gmail.com");
            myMail.Fields.Add
                ("http://schemas.microsoft.com/cdo/configuration/smtpserverport",
                              "465");
            myMail.Fields.Add
                ("http://schemas.microsoft.com/cdo/configuration/sendusing",
                              "2");

            myMail.Fields.Add
            ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
            //Use 0 for anonymous
            myMail.Fields.Add
            ("http://schemas.microsoft.com/cdo/configuration/sendusername",
                pGmailEmail);
            myMail.Fields.Add
            ("http://schemas.microsoft.com/cdo/configuration/sendpassword",
                 pGmailPassword);
            myMail.Fields.Add
            ("http://schemas.microsoft.com/cdo/configuration/smtpusessl",
                 "true");
            myMail.From = pGmailEmail;
            myMail.To = pTo;
            myMail.Subject = pSubject;
            myMail.BodyFormat = pFormat;
            myMail.Body = pBody;


            System.Web.Mail.SmtpMail.SmtpServer = "smtp.gmail.com:465";
            System.Web.Mail.SmtpMail.Send(myMail);
            return true;
        }
        catch (Exception ex)
        {
            throw;
        }
    }

    protected void btnNext_Click(object sender, EventArgs e)
    {
        int toalNoQues, cuttof;
        string user = "";
        if (txtStartDate.Text != "")
            Information.startDate = DateTime.Parse(txtStartDate.Text);
        if (txtEndDate.Text != "")
            Information.endDate = DateTime.Parse(txtEndDate.Text);
        for (int i = 0; i < UserSelection.sObj.Count; i++)
        {
            user += UserSelection.sObj[i].sid.ToString() + "|";
        }
        Information.userId = user;
        if (chkSendCumulative.Checked == true)
            Information.sendCumulativeReport = 1;
        else
            Information.sendCumulativeReport = 0;
        if (rdoLimited.Checked == true)
        {
            Information.isLimited = 1;
            Information.count = 1;
        }
        else
            Information.isLimited = 0;
        Information.Status = ddlAssignTask.SelectedItem.Text;
        if (chkNotify.Checked == true)
            Information.notifyTestTaker = 1;
        else
            Information.notifyTestTaker = 0;
        if (Information.isManualSelection == 1)
        {
            toalNoQues = Information.totalNoOfQuestionSelectedPage2;
            cuttof = Information.CuttoffmarksPage2;
        }
        else
        {
            toalNoQues = Information.totalNoOfQuestion;
            cuttof = Information.cuttOff;
        }



        if ((Request.QueryString["TestId"] == null) || (Request.QueryString["TestId"] == ""))
        {
            DataTable dtTestInfo = new DataTable();
            dtTestInfo = AdminCreateTestDAL.setTest(Information.testName, Convert.ToInt32(Information.subjectId), Information.topicId, Information.isManualSelection, toalNoQues, Information.highQuestion, Information.mediumQuestion, Information.lowQuestion, cuttof, Information.startDate, Information.endDate, Information.duration, Information.question, Information.sendCumulativeReport, Information.isLimited, Information.count, Information.refLibrary, Information.Status, Information.userId, Information.notifyTestTaker, Session["UserId"]);

            if (chkNotify.Checked == true)
            {
                lablMess.Text = "Test Created Successfully. Please Wait We are Sending Mails to test takers";
                DataSet dsEmailInfo = new DataSet();
                dsEmailInfo = AdminCreateTestDAL.GetTestCreatedInfoForMail(Convert.ToInt32(dtTestInfo.Rows[0][0]));
                string top = "";
                for (int i = 0; i < dsEmailInfo.Tables[1].Rows.Count; i++)
                {
                    top += dsEmailInfo.Tables[1].Rows[i][1].ToString() + ",";
                }
                if (top.Contains(','))
                    top = top.Remove(top.Length - 1);
                StringBuilder sbMail = new StringBuilder();
                sbMail.Append("<table width='70%'><tr><td>TestId:<b> " + dsEmailInfo.Tables[0].Rows[0][0].ToString() + "</b></td></tr>");
                sbMail.Append("<tr><td>Test Name:<b> " + dsEmailInfo.Tables[0].Rows[0][1].ToString() + "</b></td></tr><tr><td></td></tr>");
                sbMail.Append("<tr><td>Subject Name:<b> " + dsEmailInfo.Tables[0].Rows[0][2].ToString() + "</b></td></tr></table>");
                sbMail.Append("<tr><td>Topics:<b> " + top.ToString() + "</b></td></tr></table>");
                sbMail.Append("<tr><td>No Of Questions:<b> " + dsEmailInfo.Tables[0].Rows[0][3].ToString() + "</b></td></tr></table>");
                sbMail.Append("<tr><td>CutOffMarks:<b> " + dsEmailInfo.Tables[0].Rows[0][4].ToString() + "</b></td></tr></table>");
                sbMail.Append("<tr><td>Expiry Date:<b> " + dsEmailInfo.Tables[0].Rows[0][5].ToString() + "</b></td></tr></table>");
                sbMail.Append("<tr><td>Duration:<b> " + dsEmailInfo.Tables[0].Rows[0][6].ToString() + "</b></td></tr></table>");
                sbMail.Append("<tr><td><a href='http://www.skillify.net/Student/TestInfo.aspx?TestId=" + dsEmailInfo.Tables[0].Rows[0][0].ToString() + "'>Click here to go to test</a>" + "</td></tr></table>");
                string use = Information.userId;
                string[] users = use.Split('|');
                for (int k = 0; k < users.Length - 1; k++)
                {
                    DataTable dtEmail = new DataTable();
                    dtEmail = AdminCreateTestDAL.GetUserEmail(users[k]);
                    ConfigurationManager.AppSettings["ContactEmailTo"] = dtEmail.Rows[0][0].ToString();
                    if (SendEmail(ConfigurationManager.AppSettings["ContactEmailFrom"], ConfigurationManager.AppSettings["ContactEmailPassword"], ConfigurationManager.AppSettings["ContactEmailTo"], "Skillify.net - Test \"" + dsEmailInfo.Tables[0].Rows[0][1].ToString() + "\" is assigned to you", sbMail.ToString(), System.Web.Mail.MailFormat.Html, "") == true)
                    {

                    }
                }
                lablMess.Text = "Mail Send to all Test Taker Successfully.";
            }
            else
            {
                lablMess.Text = "Test Created Successfully";
            }
        }
        else
        {
            AdminCreateTestDAL.setTestUpdate(Information.testName, Convert.ToInt32(Information.subjectId), Information.topicId, Information.isManualSelection, toalNoQues, Information.highQuestion, Information.mediumQuestion, Information.lowQuestion, cuttof, Information.startDate, Information.endDate, Information.duration, Information.question, Information.sendCumulativeReport, Information.isLimited, Information.count, Information.refLibrary, Information.Status, Information.userId, Information.notifyTestTaker, Convert.ToInt32(Request.QueryString["TestId"]), Session["UserId"]);
            lablMess.Text = "Test Modified Successfully";
        }

        clearAll();

        btnMove.Visible = true;
    }

    protected void CalendarDisplay_SelectionChanged(object sender, EventArgs e)
    {


        txtStartDate.Text = CalendarDisplay.SelectedDate.ToShortDateString();
        // CalendarDisplay.Visible = false;

    }
    protected void CalendarEndDt_SelectionChanged(object sender, EventArgs e)
    {
        txtEndDate.Text = cldDisplay.SelectedDate.ToShortDateString();
    }

    protected void btnBack_Click(object sender, EventArgs e)
    {
        if (Request.QueryString["fromPage"].ToString() == "page1")
        {
            if ((Request.QueryString["TestId"] != null) && (Request.QueryString["TestId"] != ""))
                Response.Redirect("~/Admin/CreateTestPageOne.aspx?previousPage=page3&TestId=" + Request.QueryString["TestId"]);
            else if ((Request.QueryString["CopyTestId"] != null) && (Request.QueryString["CopyTestId"] != ""))
                Response.Redirect("~/Admin/CreateTestPageOne.aspx?previousPage=page3&CopyTestId=" + Request.QueryString["CopyTestId"]);
            else
                Response.Redirect("~/Admin/CreateTestPageOne.aspx?previousPage=page3");
        }
        else if (Request.QueryString["fromPage"].ToString() == "page2")
        {
            if ((Request.QueryString["TestId"] != null) && (Request.QueryString["TestId"] != ""))
                Response.Redirect("~/Admin/CreateTestPageTwo.aspx?previousPage=page3&TestId=" + Request.QueryString["TestId"]);
            else if ((Request.QueryString["CopyTestId"] != null) && (Request.QueryString["CopyTestId"] != ""))
                Response.Redirect("~/Admin/CreateTestPageTwo.aspx?previousPage=page3&CopyTestId=" + Request.QueryString["CopyTestId"]);
            else
                Response.Redirect("~/Admin/CreateTestPageTwo.aspx?previousPage=page3");
        }
    }
}